import {
	getList,
	deleteCustomer,
	editCustomer,
	addCustomer,
} from "../apis/customerAPI";
import { getPowerZoneNameMap } from "../apis/powerZoneAPI";
import { ElMessage } from "element-plus";
import { ref, reactive, onMounted } from "vue";
export const useCustomer = () => {
	/**
	 * 加载状态
	 */
	const loading = ref(false);
	// 区域Map
	const powerZoneMap = ref({});
	const powerZoneOptions = ref([]);

	const searchForm = reactive({
		customerCode: "",
		customerName: "",
		customerType: null,	
		status: null,
	});

	// 搜索
	const handleSearch = () => {
		pagination.currentPage = 1;
		LoadingCustomerList();
	};

	// 重置搜索
	const handleReset = () => {
		Object.assign(searchForm, {
			customerCode: "",
			customerName: "",
			customerType: null,
			status: null,
		});
		pagination.currentPage = 1;
		LoadingCustomerList();
	};

	// 分页信息
	const pagination = reactive({
		currentPage: 1,
		pageSize: 10,
		total: 0,
	});

	// 分页大小改变
	const handleSizeChange = (size) => {
		pagination.pageSize = size;
		LoadingCustomerList();
	};

	// 页码改变
	const handleCurrentChange = (current) => {
		pagination.currentPage = current;
		LoadingCustomerList();
	};

	// 新增对话框
	const addDialogVisible = ref(false);
	const addForm = reactive({
		customerCode: "",
		customerName: "",
		phone: "",
		address: "",
		customerType: null,
		contractCapacity: null,
		status: null,
		powerZoneId: null,
	});
	const addLoading = ref(false);

	// 打开新增对话框
	const handleAdd = () => {
		Object.assign(addForm, {
			customerCode: "",
			customerName: "",
			phone: "",
			address: "",
			customerType: null,
			contractCapacity: null,
			status: null,
			powerZoneId: null,
		});
		addDialogVisible.value = true;
	};
	
	// 获取区域列表
	const loadPowerZones = async () => {
		try {
			const response = await getPowerZoneNameMap();
			if (response.code === 200) {
				powerZoneMap.value = response.data;
				// 转换为下拉选项格式
				powerZoneOptions.value = Object.entries(response.data).map(([key, value]) => ({
					label: value,
					value: parseInt(key)
				}));
			}
		} catch (error) {
			console.error("加载区域列表失败:", error);
		}
	};
	
	// 组件挂载时加载区域列表
	onMounted(() => {
		loadPowerZones();
	});
	// 保存新增
	const saveAdd = async () => {
		addLoading.value = true;
		try {
			const response = await addCustomer(addForm);
			if (response.code === 200) {
				ElMessage.success("新增成功");
				addDialogVisible.value = false;
				LoadingCustomerList();
			} else {
				ElMessage.error(response.message || "新增失败");
			}
		} catch (error) {
			console.error("新增客户失败:", error);
			ElMessage.error("新增失败，请稍后重试");
		} finally {
			addLoading.value = false;
		}
	};

	// 客户列表
	const customerList = ref([]);

	const LoadingCustomerList = async () => {
		loading.value = true;

		try {
			const params = {
				...searchForm,
				page: pagination.currentPage,
				pageSize: pagination.pageSize,
			};
			const { code, data, message } = await getList(params);
			if (code === 200) {
				customerList.value = data.records;
				pagination.total = data.total;
			} else {
				ElMessage.error(message);
			}
		} catch (error) {
			console.error("加载客户列表失败:", error);
		} finally {
			loading.value = false;
		}
	};

	// 查看对话框
	const viewDialogVisible = ref(false);
	const viewForm = ref({});
	const handleView = (row) => {
		viewForm.value = row;
		viewDialogVisible.value = true;
	};

	// 删除功能
	const handleDelete = async (id) => {
		loading.value = true;
		try {
			const response = await deleteCustomer(id);
			if (response.code === 200) {
				ElMessage.success("删除成功");
				LoadingCustomerList();
			} else {
				ElMessage.error(response.message || "删除失败");
			}
		} catch (error) {
			console.error("删除客户失败:", error);
			ElMessage.error("删除失败，请稍后重试");
		} finally {
			loading.value = false;
		}
	};

	// 编辑功能
	const editDialogVisible = ref(false);

	// 编辑表单数据
	const editForm = reactive({
		id: "",
		customerCode: "",
		customerName: "",
		phone: "",
		address: "",
		customerType: 0,
		contractCapacity: null,
		status: 0,
		powerZoneId: null,
	});
	const editLoading = ref(false);

	const handleEdit = (row) => {
		Object.assign(editForm, row);
		editDialogVisible.value = true;
	};

	const saveEdit = async () => {
		editLoading.value = true;
		try {
			await editCustomer(editForm);
			ElMessage.success("编辑成功");
			editDialogVisible.value = false;
			LoadingCustomerList();
		} catch (error) {
			console.error("编辑客户失败:", error);
			ElMessage.error("编辑失败，请稍后重试");
		} finally {
			editLoading.value = false;
		}
	};

	// 客户类型
	const customerTypes = [
		{ label: "居民", value: 0 },
		{ label: "商业", value: 1 },
		{ label: "工业", value: 2 },
		{ label: "农业", value: 3 },
	];

	// 格式化客户类型
	const formatType = (type) => {
		const typeMap = {
			0: "居民",
			1: "商业",
			2: "工业",
			3: "农业",
		};
		return typeMap[type] || "未知";
	};
	// 格式化客户状态
	const formatStatus = (status) => {
		const statusMap = {
			0: "正常",
			1: "停用",
			2: "欠费",
		};
		return statusMap[status] || "未知";
	};

	return {
		loading,
		// 客户列表
		customerList,
		LoadingCustomerList,
		// 查看客户详情
		viewDialogVisible,
		viewForm,
		handleView,
		// 删除客户
		handleDelete,
		// 编辑客户
		editDialogVisible,
		editForm,
		saveEdit,
		handleEdit,
		customerTypes,
		editLoading,
		// 搜索表单
		searchForm,
		// 搜索
		handleSearch,
		// 重置搜索
		handleReset,

		// 分页信息
		pagination,
		// 分页切换
		handleCurrentChange,
		handleSizeChange,

		// 新增客户
		addDialogVisible,
		addForm,
		handleAdd,
		addLoading,
		saveAdd,
		// 区域相关
		powerZoneOptions,
		// 格式化方法
		formatType,
		formatStatus,
	};
};
